package com.cos.hospital.ui.record.edit;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Selection;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.RecordWebBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.UDialog;
import com.cos.hospital.tool.UKeyboard;
import com.cos.hospital.tool.UToast;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.record.RecordBaseActivity;
import com.cos.hospital.ui.record.RecordCode;
import com.cos.hospital.ui.record.adapter.AdapterFormula;
import com.cos.hospital.ui.record.bean.BeanFormula;
import com.cos.hospital.widget.EasySwipeMenuLayout;
import com.cos.hospital.widget.KKeyboardView;
import com.cos.hospital.widget.MyDividerDecoration;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;
import com.jude.utils.JUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * @Description: 编辑: 经产史
 * @Author: Kosmos
 * @Date: 2018年09月26日 20:52
 * @Email: KosmoSakura@foxmail.com
 */
public class EditorMenstruationActivity extends RecordBaseActivity implements View.OnTouchListener, View.OnFocusChangeListener {
    private final int StateInit = 0;
    private final int StateFail = 1;
    private final int StateSuccess = 2;
    protected List<BeanFormula> listFormula;
    protected AdapterFormula adapterFormula;
    @BindView(R.id.rec_edt_main_lay)
    View rootLay;
    @BindView(R.id.rc_formula)
    RecyclerView rvFormula;
    @BindView(R.id.formula_lmp_first)
    EditText lmpA;
    @BindView(R.id.formula_lmp_b1)
    EditText lmpB1;
    @BindView(R.id.formula_lmp_b2)
    EditText lmpB2;
    @BindView(R.id.formula_lmp_c1)
    EditText lmpC1;
    @BindView(R.id.formula_lmp_c2)
    EditText lmpC2;
    @BindView(R.id.formula_lmp_end)
    TextView lmpEnd;
    @BindView(R.id.formula_lmp_first_2)
    EditText lmp2A;
    @BindView(R.id.formula_lmp_b1_2)
    EditText lmp2B1;
    @BindView(R.id.formula_lmp_b2_2)
    EditText lmp2B2;
    @BindView(R.id.formula_lmp_c1_2)
    EditText lmp2C1;
    @BindView(R.id.formula_lmp_c2_2)
    EditText lmp2C2;
    @BindView(R.id.formula_lmp_end_2)
    EditText lmpEnd2;
    @BindView(R.id.formula_gp_g)
    EditText gpG;
    @BindView(R.id.formula_gp_plost)
    EditText gpLost;
    @BindView(R.id.formula_gp_plabor)
    EditText gpLabor;
    @BindView(R.id.formula_gp_mark)
    EditText gpMark;
    @BindView(R.id.formula_br_full)
    EditText brFull;
    @BindView(R.id.formula_br_early)
    EditText brEarly;
    @BindView(R.id.formula_br_fail)
    EditText brFail;
    @BindView(R.id.formula_br_alive)
    EditText brAlive;
    @BindView(R.id.m_lmp_esl)
    EasySwipeMenuLayout eslLmp1;
    @BindView(R.id.m_lmp2_esl)
    EasySwipeMenuLayout eslLmp2;
    @BindView(R.id.m_gp_esl)
    EasySwipeMenuLayout eslGP;
    @BindView(R.id.m_br_esl)
    EasySwipeMenuLayout eslBr;
    @BindView(R.id.mens_keyboard)
    KKeyboardView keyboardView;
    private int bEle, bLmp, bBr, bGp;
    private RecordWebBean.MhfBean mhfBean;//月经史公式返回
    private RecordWebBean.RhfBean rhfBean;//生育史公式返回
    private int mhfID, rhfId;

    @Override
    protected int layout() {
        return R.layout.activity_editor_menstruation;
    }

    @Override
    protected void initData() {
        setTitleLeftIcon();
        setTitleCenterTxt(getString(R.string.menstruation_edit));
        setTitleRightTxt(getString(R.string.save));
        edtMain.setHint(R.string.please_enter_menstruation);
        changeBtnState(tVoice, StateOFF);
        changeBtnState(tTemplate, StateOFF);
        changeBtnState(tFormula, StateOFF);
        changeBtnState(tTakephoto, StateNone);
        initTemplateAdapter();
        listFormula = new ArrayList<>();
        adapterFormula = new AdapterFormula(listFormula);
        adapterFormula.openLoadAnimation();//开启默认动画AlphaInAnimation
        rvFormula.setLayoutManager(new LinearLayoutManager(context));
        adapterFormula.setEmptyView(R.layout.lay_empty, rvFormula);//设置当list中元素个数为0时显示的布局
        rvFormula.addItemDecoration(new MyDividerDecoration(ContextCompat.getColor(context, R.color.white_bg), JUtils.dip2px(1)));
        rvFormula.setAdapter(adapterFormula);

        Intent intent = getIntent();
        mhfID = intent.getIntExtra("mhf_id", 0);
        rhfId = intent.getIntExtra("rhf_id", 0);
        //月经史公式
        RecordWebBean.MhfBean mhfBean = (RecordWebBean.MhfBean) intent.getSerializableExtra(Code.Actions.MHF_KEY);
        if (mhfBean == null) {
            eslLmp1.setVisibility(View.GONE);
            eslLmp2.setVisibility(View.GONE);
        } else {
            //公式类型(0以年龄,1日期)
            if (mhfBean.getFldType() == 1) {
                eslLmp1.setVisibility(View.VISIBLE);
                eslLmp2.setVisibility(View.GONE);
                lmpA.setText(UTxt.isNullStr(mhfBean.getFldMenarcheAge(), 0));//初潮年龄
                lmpB1.setText(UTxt.isNullStr(mhfBean.getFldMinPeriod(), 0));//经期范围a
                lmpB2.setText(UTxt.isNullStr(mhfBean.getFldMaxPeriod(), 0));//经期范围b
                lmpC1.setText(UTxt.isNullStr(mhfBean.getFldMinCycle(), 0));//周期范围a
                lmpC2.setText(UTxt.isNullStr(mhfBean.getFldMaxCycle(), 0));//周期范围b
                lmpEnd.setText(UTxt.isNull(UDate.strToStrSafety(mhfBean.getFldLmp(), "yyyy-MM-dd")));//末次月经日期
            } else {
                eslLmp1.setVisibility(View.GONE);
                eslLmp2.setVisibility(View.VISIBLE);
                lmp2A.setText(UTxt.isNullStr(mhfBean.getFldMenarcheAge(), 0));//初潮年龄
                lmp2B1.setText(UTxt.isNullStr(mhfBean.getFldMinPeriod(), 0));//经期范围a
                lmp2B2.setText(UTxt.isNullStr(mhfBean.getFldMaxPeriod(), 0));//经期范围b
                lmp2C1.setText(UTxt.isNullStr(mhfBean.getFldMinCycle(), 0));//周期范围a
                lmp2C2.setText(UTxt.isNullStr(mhfBean.getFldMaxCycle(), 0));//周期范围b
                lmpEnd2.setText(UTxt.isNullStr(mhfBean.getFldMenopauseAge(), 0));//绝经年龄
            }
        }
        //生育史公式
        RecordWebBean.RhfBean rhfBean = (RecordWebBean.RhfBean) intent.getSerializableExtra(Code.Actions.RHF_KEY);
        if (rhfBean == null) {
            eslBr.setVisibility(View.GONE);//1表现形式1
            eslGP.setVisibility(View.GONE);//2表现形式2
        } else {
            //公式类型(1表现形式1,2表现形式2) ,
            if (rhfBean.getFldType() == 1) {
                eslBr.setVisibility(View.VISIBLE);
                eslGP.setVisibility(View.GONE);
                brFull.setText(UTxt.isNullStr(rhfBean.getFldTermDelivery(), 0));//足月产
                brEarly.setText(UTxt.isNullStr(rhfBean.getFldPrematureDelivery(), 0));//早产
                brFail.setText(UTxt.isNullStr(rhfBean.getFldAbortion(), 0));//流产
                brAlive.setText(UTxt.isNullStr(rhfBean.getFldChildrenNum(), 0));//现存子女数
            } else {
                eslBr.setVisibility(View.GONE);
                eslGP.setVisibility(View.VISIBLE);
                gpG.setText(UTxt.isNullStr(rhfBean.getFldPregnancy(), 0));//孕 次数
                gpLost.setText(UTxt.isNullStr(rhfBean.getFldAbortion(), 0));//流产 表现形式2
                gpLabor.setText(UTxt.isNullStr(rhfBean.getFldParturition(), 0));//产 表现形式2
                gpMark.setText(UTxt.isNull(rhfBean.getFldDesc()));//备注
            }
        }
        rootLay.setOnTouchListener(this);
        edtMain.setOnTouchListener(this);
        gpMark.setOnTouchListener(this);
        //禁止Edittext弹出软件盘
        EditText[] viewArr = {lmpA, lmpB1, lmpB2, lmpC1, lmpC2, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2,
            lmpEnd2, gpG, gpLost, gpLabor, brFull, brEarly, brAlive, brFail};
        for (EditText edt : viewArr) {
            MyUtil.getInstance().disableShowSoftInput(edt);
            edt.setOnFocusChangeListener(this);
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        hideAnything();
        if (view.getId() == R.id.rec_edt_main_lay ||
            view.getId() == R.id.rec_edt_main) {
            UKeyboard.with(this).showForce(edtMain);
        } else {
            UKeyboard.with(this).showForce((EditText) view);
        }
        return false;
    }

    @Override
    protected void logic() {
        adapterFormula.setOnItemClickListener((adapter, view, position) -> {
            if (position < 0 || position >= listFormula.size()) {
                return;
            }
            BeanFormula formulaBean = listFormula.get(position);
            switch (formulaBean.getFormulaId()) {
                case RecordCode.FormulaId.FID_GP://孕产史:
                    if (eslGP.isShown()) {
                        showNotice("当前公式已经加载");
                        return;
                    }
                    eslGP.setVisibility(View.VISIBLE);
                    hideAnything();
                    break;
                case RecordCode.FormulaId.FID_Birth://生育史:
                    if (eslBr.isShown()) {
                        showNotice("当前公式已经加载");
                        return;
                    }
                    eslBr.setVisibility(View.VISIBLE);
                    hideAnything();
                    break;
            }
        });
        adapterFormula.setOnItemChildClickListener((adapter, view, position) -> {
            if (position < 0 || position >= listFormula.size()) {
                return;
            }
            BeanFormula formulaBean = listFormula.get(position);
            switch (formulaBean.getFormulaId()) {
                case RecordCode.FormulaId.FID_LMP_1://月经史1:
                case RecordCode.FormulaId.FID_LMP_2://月经史2:
                    if (view.getId() == R.id.formula_1) {
                        eslLmp1.setVisibility(View.VISIBLE);
                        eslLmp2.setVisibility(View.GONE);
                    } else {
                        eslLmp2.setVisibility(View.VISIBLE);
                        eslLmp1.setVisibility(View.GONE);
                    }
                    hideAnything();
                    break;
                case RecordCode.FormulaId.FID_GP://孕产史:
                    if (eslGP.isShown()) {
                        showNotice("当前公式已经加载");
                        return;
                    }
                    if (eslBr.isShown()) {
                        eslBr.setVisibility(View.GONE);
                    }
                    eslGP.setVisibility(View.VISIBLE);
                    hideAnything();
                    break;
                case RecordCode.FormulaId.FID_Birth://生育史:
                    if (eslBr.isShown()) {
                        showNotice("当前公式已经加载");
                        return;
                    }
                    if (eslGP.isShown()) {
                        eslGP.setVisibility(View.GONE);
                    }
                    eslBr.setVisibility(View.VISIBLE);
                    hideAnything();
                    break;
            }
        });
        Selection.setSelection(edtMain.getText(), edtMain.length());
    }

    @Override
    protected void onTemplateSelect(String content) {
//        edtMain.append(content);
//        Selection.setSelection(edtMain.getText(), edtMain.length());
        int index = edtMain.getSelectionStart();
        Editable edit = edtMain.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edtMain.append(content);
        } else {
            edit.insert(index, content);
        }
    }

    /**
     * @param state 状态
     * @apiNote :
     * int FunVoice = 1;//语音
     * int FunTemplate = 1;//模板
     * int FunFormula = 1;//公式
     */
    @Override
    protected void onFunctionBtnClick(int state) {
        keyboardView.hide();
        switch (state) {
            case FunTemplate:
                if (firstTimeToGetTemplateList) {
                    spv.callFreshDelay(500);
                    firstTimeToGetTemplateList = false;
                }
                break;
            case FunFormula://公式:
                listFormula.clear();
                listFormula.add(new BeanFormula(RecordCode.FormulaId.FID_LMP_1));
                listFormula.add(new BeanFormula(RecordCode.FormulaId.FID_GP));
                listFormula.add(new BeanFormula(RecordCode.FormulaId.FID_Birth));
                adapterFormula.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void onSpeakBack(String result) {
        int index = edtMain.getSelectionStart();
        Editable edit = edtMain.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edtMain.append(result);
        } else {
            edit.insert(index, result);
        }
    }

    private void save() {
        if (UTxt.isEmpty(edtMain) && !eslLmp1.isShown() && !eslLmp2.isShown()
            && !eslGP.isShown() && !eslBr.isShown()) {
            showNotice("保存内容不能为空");
            return;
        }
        int mpAge = 0, mpB1 = 0, mpB2 = 0, mpC1 = 0, mpC2 = 0, mpEnd1 = 0;
        String mpEnd2 = "";
        //月经史公式1
        if (eslLmp1.isShown()) {
            mpEnd2 = lmpEnd.getText().toString();//最后一次月经
            if (UTxt.isEmpty(mpEnd2)) {
                showNotice("公式内容不规范");
                return;
            }
            try {
                mpAge = Integer.parseInt(lmpA.getText().toString());
                mpB1 = Integer.parseInt(lmpB1.getText().toString());
                mpB2 = Integer.parseInt(lmpB2.getText().toString());
                mpC1 = Integer.parseInt(lmpC1.getText().toString());
                mpC2 = Integer.parseInt(lmpC2.getText().toString());
            } catch (NumberFormatException e) {
                showNotice("公式内容不规范");
                return;
            }
        }
        //月经史公式2
        if (eslLmp2.isShown()) {
            try {
                mpAge = Integer.parseInt(lmp2A.getText().toString());
                mpB1 = Integer.parseInt(lmp2B1.getText().toString());
                mpB2 = Integer.parseInt(lmp2B2.getText().toString());
                mpC1 = Integer.parseInt(lmp2C1.getText().toString());
                mpC2 = Integer.parseInt(lmp2C2.getText().toString());
                mpEnd1 = Integer.parseInt(lmpEnd2.getText().toString());
            } catch (NumberFormatException e) {
                showNotice("公式内容不规范");
                return;
            }
        }
        //（生育史公式） 表现形式1
        int fldTermDelivery = 0, fldPrematureDelivery = 0, fldAbortion = 0, fldChildrenNum = 0;
        if (eslBr.isShown()) {
            try {
                fldTermDelivery = Integer.parseInt(brFull.getText().toString());//足月产次数
                fldPrematureDelivery = Integer.parseInt(brEarly.getText().toString());//早产
                fldAbortion = Integer.parseInt(brFail.getText().toString());//流产
                fldChildrenNum = Integer.parseInt(brAlive.getText().toString());//现存子女数
            } catch (NumberFormatException e) {
                showNotice("公式内容不规范");
                return;
            }
        }

        //（生育史公式） 表现形式2
        int fldPregnancy = 0, birth = 0;
        String mark = "";
        if (eslGP.isShown()) {
            mark = gpMark.getText().toString();//备注
            if (UTxt.isEmpty(mark)) {
                showNotice("公式内容不规范");
                return;
            }
            try {
                fldPregnancy = Integer.parseInt(gpG.getText().toString());//怀孕次数
                fldAbortion = Integer.parseInt(gpLost.getText().toString());//流产
                birth = Integer.parseInt(gpLabor.getText().toString());//分娩次数
            } catch (NumberFormatException e) {
                showNotice("公式内容不规范");
                return;
            }
        }

        ProgressDialog.getInstance().startProgressDialog(this);
        saveEle(mpAge, mpB1, mpB2, mpC1, mpC2, mpEnd2, mpEnd1, fldTermDelivery, fldPrematureDelivery,
            fldChildrenNum, fldPregnancy, mark, birth, fldAbortion);
    }

    private void saveDown() {
        //说明并发请求未完成
        if (bEle == StateInit) {
            return;
        }
        if ((eslLmp1.isShown() || eslLmp2.isShown()) && bLmp == StateInit) {
            return;
        }
        if (eslBr.isShown() && bBr == StateInit) {
            return;
        }
        if (eslGP.isShown() && bGp == StateInit) {
            return;
        }

        ProgressDialog.getInstance().stopProgressDialog();
        Intent intent = new Intent();
        String text = "";
        //元素保存
        if (bEle == StateSuccess) {
            intent.putExtra(Code.SP.CONTENT, edtMain.getText().toString());
        } else {
            text = "元素保存失败";
        }

        //月经史公式
        if (eslLmp1.isShown() || eslLmp2.isShown()) {
            if (bLmp == StateSuccess && mhfBean != null) {
                intent.putExtra(Code.Actions.MHF_KEY, mhfBean);
            } else {
                text = "月经史保存失败";
            }
        }
        //生育史公式
        if (eslBr.isShown()) {
            if (bBr == StateSuccess && rhfBean != null) {
                intent.putExtra(Code.Actions.RHF_KEY, rhfBean);
            } else {
                text = "生育史保存失败";
            }
        }
        //孕产史公式
        if (eslGP.isShown()) {
            if (bGp == StateSuccess && rhfBean != null) {
                intent.putExtra(Code.Actions.RHF_KEY, rhfBean);
            } else {
                text = "孕产史保存失败";
            }
        }
        if (UTxt.isEmpty(text)) {
            UToast.toast("保存成功");
            intent.putExtra(Code.SP.ID, eId);
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else {
            UToast.toast(text);
        }
    }

    /**
     * 保存元素
     */
    private void saveEle(int finalMpAge, int finalMpB, int finalMpB1, int finalMpC, int finalMpC1,
                         String finalMpEnd, int finalMpEnd1, int finalFldTermDelivery,
                         int finalFldPrematureDelivery, int finalFldChildrenNum,
                         int fldPregnancy, String finalMark, int birth, int fldAbortion) {

        bEle = StateInit;
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldMedicalHistoryId", fldMedicalHistoryId);//病历ID
        jsonObject.addProperty("fldEleID", fldEleID);//元素唯一id
        jsonObject.addProperty("fldElementValue", UTxt.isNull(edtMain.getText().toString()));//元素内容
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());//编辑人id
        UHttp.start(getServes().saveMedicalElement(jsonObject), "经产史元素保存",
            new HttpMsgListener<ResultBean<RecordWebBean.MedicalElementBean>>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    addEvent(disposable);
                }

                @Override
                public void onError(String describe) {
                    bEle = StateFail;
                }

                @Override
                public void onFinish() {
                    saveDown();
                }

                @Override
                public void onSuccess(ResultBean<RecordWebBean.MedicalElementBean> dto) {
                    if (dto.isSuccess()) {
                        bEle = StateSuccess;
                        RecordWebBean.MedicalElementBean medicalElementBean = dto.getResult();
                        if (medicalElementBean != null) {
                            eId = medicalElementBean.getId();
                        }
                        //月经史公式1
                        if (eslLmp1.isShown()) {
                            saveEleMHF_1(finalMpAge, finalMpB, finalMpB1, finalMpC, finalMpC1, finalMpEnd);
                        }
                        //月经史公式2
                        if (eslLmp2.isShown()) {
                            saveEleMHF_2(finalMpAge, finalMpB, finalMpB1, finalMpC, finalMpC1, finalMpEnd1);
                        }
                        //（生育史公式） 表现形式1
                        if (eslBr.isShown()) {
                            saveEleRHF_1(finalFldTermDelivery, finalFldPrematureDelivery, fldAbortion, finalFldChildrenNum);
                        }
                        //（孕产史公式） 表现形式2
                        if (eslGP.isShown()) {
                            saveEleRHF_2(finalMark, fldPregnancy, birth, fldAbortion);
                        }
                    } else {
                        bEle = StateFail;
                    }
                }
            });
    }

    /**
     * 保存元素（月经史公式1）
     */
    private void saveEleMHF_1(int age, int b1, int b2, int c1, int c2, String end) {
        bLmp = StateInit;
        HashMap<String, Object> map = new HashMap<>();
        map.put("fldParentElementId", eId);
        map.put("fldMedicalHistoryId", fldMedicalHistoryId);//病历ID
        map.put("fldEditId", SPUtil.getUserId());//编辑人id
        map.put("fldMenarcheAge", age);//初潮年龄
        map.put("fldMinPeriod", Math.min(b1, b2));//经期范围b（较小值）
        map.put("fldMaxPeriod", Math.max(b1, b2));//经期范围b（较大值）
        map.put("fldMinCycle", Math.min(c1, c2));//周期范围a（较小值）
        map.put("fldMaxCycle", Math.max(c1, c2));//周期范围a（较大值）
        map.put("fldLmp", end);//末次月经日期
        map.put("fldType", 1);//公式类型(0以年龄,1日期)
        UHttp.start(getServes().saveMedicalMHF(map), "月经史公式1元素保存",
            new HttpMsgListener<ResultBean<RecordWebBean.MhfBean>>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    addEvent(disposable);
                }

                @Override
                public void onError(String describe) {
                    bLmp = StateFail;
                }

                @Override
                public void onFinish() {
                    saveDown();
                }

                @Override
                public void onSuccess(ResultBean<RecordWebBean.MhfBean> dto) {
                    mhfBean = dto.getResult();
                    bLmp = dto.isSuccess() ? StateSuccess : StateFail;
                }
            });
    }

    /**
     * 保存元素（月经史公式2）
     */
    private void saveEleMHF_2(int age, int b1, int b2, int c1, int c2, int end) {
        bLmp = StateInit;
        HashMap<String, Object> map = new HashMap<>();
        map.put("fldParentElementId", eId);
        map.put("fldMedicalHistoryId", fldMedicalHistoryId);//病历ID
        map.put("fldEditId", SPUtil.getUserId());//编辑人id
        map.put("fldMenarcheAge", age);//初潮年龄
        map.put("fldMinPeriod", Math.min(b1, b2));//经期范围b（较小值）
        map.put("fldMaxPeriod", Math.max(b1, b2));//经期范围b（较大值）
        map.put("fldMinCycle", Math.min(c1, c2));//周期范围a（较小值）
        map.put("fldMaxCycle", Math.max(c1, c2));//周期范围a（较大值）
        map.put("fldMenopauseAge", end);//绝经年龄
        map.put("fldType", 0);//公式类型(0以年龄,1日期)
        UHttp.start(getServes().saveMedicalMHF(map), "月经史公式2元素保存",
            new HttpMsgListener<ResultBean<RecordWebBean.MhfBean>>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    addEvent(disposable);
                }

                @Override
                public void onError(String describe) {
                    bLmp = StateFail;
                }

                @Override
                public void onFinish() {
                    saveDown();
                }

                @Override
                public void onSuccess(ResultBean<RecordWebBean.MhfBean> dto) {
                    bLmp = dto.isSuccess() ? StateSuccess : StateFail;
                    mhfBean = dto.getResult();
                }
            });
    }

    /**
     * 保存元素（生育史公式） 表现形式1
     */
    private void saveEleRHF_1(int fldTermDelivery, int fldPrematureDelivery, int fldAbortion, int fldChildrenNum) {
        bBr = StateInit;
        HashMap<String, Object> map = new HashMap<>();
        map.put("fldParentElementId", eId);
        map.put("fldMedicalHistoryId", fldMedicalHistoryId);//病历ID
        map.put("fldEditId", SPUtil.getUserId());//编辑人id
        map.put("fldChildrenNum", fldChildrenNum);//现存子女数 表现形式1
        map.put("fldAbortion", fldAbortion);//流产 表现形式1
        map.put("fldPrematureDelivery", fldPrematureDelivery);//早产 表现形式1
        map.put("fldTermDelivery", fldTermDelivery);//足月产 表现形式1
        map.put("fldType", 1);//公式类型(1表现形式1,2表现形式2) ,
        UHttp.start(getServes().saveMedicalRHF(map), "生育史公式1元素保存",
            new HttpMsgListener<ResultBean<RecordWebBean.RhfBean>>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    addEvent(disposable);
                }

                @Override
                public void onError(String describe) {
                    bBr = StateFail;
                }

                @Override
                public void onFinish() {
                    saveDown();
                }

                @Override
                public void onSuccess(ResultBean<RecordWebBean.RhfBean> dto) {
                    rhfBean = dto.getResult();
                    bBr = dto.isSuccess() ? StateSuccess : StateFail;
                }
            });
    }

    /**
     * 保存元素（生育史公式） 表现形式2
     */
    private void saveEleRHF_2(String mark, int fldPregnancy, int birth, int fldAbortion) {
        bGp = StateInit;
        HashMap<String, Object> map = new HashMap<>();
        map.put("fldParentElementId", eId);
        map.put("fldMedicalHistoryId", fldMedicalHistoryId);//病历ID
        map.put("fldEditId", SPUtil.getUserId());//编辑人id
        map.put("fldPregnancy", fldPregnancy);//怀孕 表现形式2 ,
        map.put("fldParturition", birth);//分娩 表现形式2 ,
        map.put("fldAbortion", fldAbortion);//流产 表现形式1
        map.put("fldDesc", mark);//备注 表现形式2 ,
        map.put("fldType", 2);//公式类型(1表现形式1,2表现形式2) ,
        UHttp.start(getServes().saveMedicalRHF(map), "生育史公式2元素保存",
            new HttpMsgListener<ResultBean<RecordWebBean.RhfBean>>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    addEvent(disposable);
                }

                @Override
                public void onError(String describe) {
                    bGp = StateFail;
                }

                @Override
                public void onFinish() {
                    saveDown();
                }

                @Override
                public void onSuccess(ResultBean<RecordWebBean.RhfBean> dto) {
                    bGp = dto.isSuccess() ? StateSuccess : StateFail;
                    rhfBean = dto.getResult();
                }
            });
    }

    @OnClick({R.id.title_next_txt, R.id.formula_lmp_root, R.id.formula_lmp_root_2,
        R.id.formula_gp_root, R.id.formula_br_root, R.id.m_lmp_right, R.id.m_lmp2_right,
        R.id.m_gp_right, R.id.m_br_right, R.id.formula_lmp_end})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.title_next_txt://保存:
                UKeyboard keyboard = UKeyboard.with(this);
                if (keyboard.isKeyboardShow()) {
                    keyboard.hideForce(edtMain);
                }
                save();
                break;
            case R.id.formula_lmp_root:
                eslLmp1.resetStatus();
                break;
            case R.id.formula_lmp_root_2:
                eslLmp1.resetStatus();
                break;
            case R.id.formula_gp_root:
                eslLmp1.resetStatus();
                break;
            case R.id.formula_br_root:
                eslLmp1.resetStatus();
                break;
            case R.id.formula_lmp_end://时间:
                showDatePicker();
                break;
            case R.id.m_lmp_right:
                UDialog.getInstance(context, true, true)
                    .showNoticeWithTwobtn("删除当前公式？", (result, dia) -> {
                        eslLmp1.setVisibility(View.GONE);
                        dia.dismiss();
                        deleteMHF();
                    });
                break;
            case R.id.m_lmp2_right:
                UDialog.getInstance(context, true, true)
                    .showNoticeWithTwobtn("删除当前公式？", (result, dia) -> {
                        eslLmp2.setVisibility(View.GONE);
                        dia.dismiss();
                        deleteMHF();
                    });
                break;
            case R.id.m_gp_right:
                UDialog.getInstance(context, true, true)
                    .showNoticeWithTwobtn("删除当前公式？", (result, dia) -> {
                        eslGP.setVisibility(View.GONE);
                        dia.dismiss();
                        deleteRHF();
                    });
                break;
            case R.id.m_br_right:
                UDialog.getInstance(context, true, true)
                    .showNoticeWithTwobtn("删除当前公式？", (result, dia) -> {
                        eslBr.setVisibility(View.GONE);
                        dia.dismiss();
                        deleteRHF();
                    });
                break;
        }
    }

    @OnClick({R.id.formula_lmp_first, R.id.formula_lmp_b1, R.id.formula_lmp_b2, R.id.formula_lmp_c1,
        R.id.formula_lmp_c2, R.id.formula_lmp_end, R.id.formula_lmp_first_2, R.id.formula_lmp_b1_2,
        R.id.formula_lmp_b2_2, R.id.formula_lmp_c1_2, R.id.formula_lmp_c2_2, R.id.formula_lmp_end_2,
        R.id.formula_gp_g, R.id.formula_gp_plost, R.id.formula_gp_plabor, R.id.formula_gp_mark,
        R.id.formula_br_full, R.id.formula_br_early, R.id.formula_br_fail, R.id.formula_br_alive})
    public void onTextClicked(View view) {
        if (view.getId() != R.id.formula_gp_mark) {
            UKeyboard.with(this).hideForce(edtMain);
        }
        hideAllFun();
        showKView(view);
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        UKeyboard.with(this).hideForce(edtMain);
        hideAllFun();
        if (!hasFocus) {
//            keyboardView.hide();
        } else {
            showKView(view);
        }
    }

    private void showKView(View view) {
        switch (view.getId()) {
            //经产1
            case R.id.formula_lmp_first:
                keyboardView.setInputText(0, lmpA, lmpB1, lmpB2, lmpC1, lmpC2);
                break;
            case R.id.formula_lmp_b1:
                keyboardView.setInputText(1, lmpA, lmpB1, lmpB2, lmpC1, lmpC2);
                break;
            case R.id.formula_lmp_b2:
                keyboardView.setInputText(2, lmpA, lmpB1, lmpB2, lmpC1, lmpC2);
                break;
            case R.id.formula_lmp_c1:
                keyboardView.setInputText(3, lmpA, lmpB1, lmpB2, lmpC1, lmpC2);
                break;
            case R.id.formula_lmp_c2:
                keyboardView.setInputText(4, lmpA, lmpB1, lmpB2, lmpC1, lmpC2);
                break;
            //经产2
            case R.id.formula_lmp_first_2:
                keyboardView.setInputText(0, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2, lmpEnd2);
                break;
            case R.id.formula_lmp_b1_2:
                keyboardView.setInputText(1, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2, lmpEnd2);
                break;
            case R.id.formula_lmp_b2_2:
                keyboardView.setInputText(2, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2, lmpEnd2);
                break;
            case R.id.formula_lmp_c1_2:
                keyboardView.setInputText(3, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2, lmpEnd2);
                break;
            case R.id.formula_lmp_c2_2:
                keyboardView.setInputText(4, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2, lmpEnd2);
                break;
            case R.id.formula_lmp_end_2:
                keyboardView.setInputText(5, lmp2A, lmp2B1, lmp2B2, lmp2C1, lmp2C2, lmpEnd2);
                break;
            //孕产史1
            case R.id.formula_gp_g:
                keyboardView.setInputText(0, gpG, gpLost, gpLabor);
                break;
            case R.id.formula_gp_plost:
                keyboardView.setInputText(1, gpG, gpLost, gpLabor);
                break;
            case R.id.formula_gp_plabor:
                keyboardView.setInputText(2, gpG, gpLost, gpLabor);
                break;
            case R.id.formula_gp_mark://备注
                break;
            //孕产史2
            case R.id.formula_br_full:
                keyboardView.setInputText(0, brFull, brEarly, brFail, brAlive);
                break;
            case R.id.formula_br_early:
                keyboardView.setInputText(1, brFull, brEarly, brFail, brAlive);
                break;
            case R.id.formula_br_fail:
                keyboardView.setInputText(2, brFull, brEarly, brFail, brAlive);
                break;
            case R.id.formula_br_alive:
                keyboardView.setInputText(3, brFull, brEarly, brFail, brAlive);
                break;
        }
    }

    @Override
    protected void hideInputAll() {
        hideAnything();
    }

    private void hideAnything() {
        keyboardView.hide();
        hideAllFun();
    }

    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(this, R.style.KDatePicker,
            (view, year, month, dayOfMonth) ->
                lmpEnd.setText(year + "-" + (month + 1) + "-" + dayOfMonth)
            , calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
        dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        dialog.show();
    }

    /**
     * @param position 侧滑删除月经公式
     */
    private void deleteMHF() {
        if (mhfID == 0) {
            return;
        }
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", mhfID);
        UHttp.start(getServes().deleteMedicalMHF(jsonObject), "删除月经公式", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    showNotice("删除成功");
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * @param position 侧滑删除孕产+生育公式
     */
    private void deleteRHF() {
        if (rhfId == 0) {
            return;
        }
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", rhfId);
        UHttp.start(getServes().deleteMedicalRHF(jsonObject), "删除除孕产+生育公式", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    showNotice("删除成功");
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }
}
